package org.geektimes.configuration.microprofile.source.servlet;

import org.geektimes.configuration.microprofile.source.BesedConfigSource;
import org.geektimes.configuration.microprofile.source.MapBesedConfigSource;

import javax.servlet.ServletContext;
import java.util.*;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/3/21 19:30
 */
public class ServletContextConfigSource extends BesedConfigSource {

    private final ServletContext servletContext;
    private final Map<String,String> source;

    public ServletContextConfigSource(ServletContext servletContext) {
        super("ServletContext Init Parameters", 500);
        this.servletContext = servletContext;
        source = getProperties();
    }


    @Override
    public final Map<String, String> getProperties() {
        Map<String, String> configData = new HashMap<>();
        try {
            Enumeration<String> parameterNames = servletContext.getInitParameterNames();
            while (parameterNames.hasMoreElements()){
                String parameterName = parameterNames.nextElement();
                configData.put(parameterName,servletContext.getInitParameter(parameterName));
            }
        } catch (Throwable e) {
            throw new IllegalArgumentException("准备配置数据发送错误", e);
        }
        return Collections.unmodifiableMap(configData);
    }

    @Override
    public Set<String> getPropertyNames() {
        return source.keySet();
    }

    @Override
    public String getValue(String propertyName) {
        return source.get(propertyName);
    }
}
